package ThreadCommunication.ReentrantLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dycong
 * @date 2018/5/5 19:20
 */
public class Account {
    private double balance;
    // 标识账户中是否已有存款
    private boolean flag = false;

    private final Lock lock = new ReentrantLock();            /////////修改之处////////
    private final Condition condition = lock.newCondition();  /////////修改之处////////

    public Account(double balance){
        this.balance = balance;
    }

    public void draw(double drawAmount){
        lock.lock();       /////////修改之处////////
        try {
            if (!flag){
                condition.await();      /////////修改之处////////
            }
            else {
                //执行取款操作
                System.out.println(Thread.currentThread().getName() + " 取钱：" + drawAmount);
                balance -= drawAmount;
                System.out.println("账户余额为：" + balance);
                // 账户中存款被取走，将标志flag设为false
                flag = false;
                // 唤醒其他线程
                condition.signalAll();  /////////修改之处////////
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public void deposit(double depositAmount){
        lock.lock();       /////////修改之处////////
        try {
            if (flag){
                condition.await();      /////////修改之处////////
            }
            else {
                //执行存款操作
                System.out.println(Thread.currentThread().getName() + " 存款：" + depositAmount);
                balance += depositAmount;
                System.out.println("账户余额为：" + balance);
                // 账户中已有存款，将标志flag设为true
                flag = true;
                // 唤醒其他线程
                condition.signalAll();  /////////修改之处////////
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
